package com.neusoft.neuiotms.dcvm.task.cmdbSyn.service.impl;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.neusoft.bizcore.web.exception.UnitedException;
import com.neusoft.neuiotms.dcvm.dto.ConfigDTO;
import com.neusoft.neuiotms.dcvm.service.ConfigService;
import com.neusoft.neuiotms.dcvm.task.cmdbSyn.service.ItSynApiService;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class ItSynApiServiceImpl implements ItSynApiService {
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private ConfigService configService;

    @Override
    public JSONObject getItDevicesData() {
        final String url = this.getUrl("getItDevicesData");

        // 1、   设置同步IT设备拉取范围：在【配置中心-3D配置】中 "synItRoomCodes" 设置本期业务涉及的房间
        final String synItRoomCodes = this.configService.details(CmdbSynServiceImpl.SYNITROOMCODES).getData();

        final HttpHeaders headers = new HttpHeaders();
        final MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());

        final JSONObject param = new JSONObject();
        param.put("roomCodes", Arrays.asList(synItRoomCodes.split(",")));
        final HttpEntity<String> entity = new HttpEntity<>(param.toString(), headers);

        final ParameterizedTypeReference<JSONObject> typeRef = new ParameterizedTypeReference<JSONObject>() {
        };

        ItSynApiServiceImpl.log.info("调用运管系统源接口: {}, params={}", url, param.toString());

        final ResponseEntity<JSONObject> response = this.restTemplate.exchange(url, HttpMethod.POST, entity, typeRef);
        if (null == response) {
            throw new UnitedException(url + "查询失败");
        }

        final JSONObject result = response.getBody();

        return result;
    }

    @Override
    public JSONObject getRackListData() {
        final String url = this.getUrl("getRackListData");
        final String synItRoomCodes = this.configService.details("synItRoomCodes").getData();
        final ParameterizedTypeReference<JSONObject> typeRef = new ParameterizedTypeReference<JSONObject>() {
        };

        final HttpHeaders headers = new HttpHeaders();
        final MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());

        final JSONObject param = new JSONObject();
        param.put("roomCodes", Arrays.asList(synItRoomCodes.split(",")));
        final HttpEntity<String> entity = new HttpEntity<>(param.toString(), headers);

        final ResponseEntity<JSONObject> response = this.restTemplate.exchange(url, HttpMethod.POST, entity, typeRef);
        if (null == response) {
            throw new UnitedException(url + "查询失败");
        }
        final JSONObject result = response.getBody();
        return result;
    }

    private String getUrl(final String code) {
        final ConfigDTO details = this.configService.details(code);
        return details.getData();
    }

    @Override
    public JSONObject getMockItDevicesData() {

        InputStream fis = null;
        try {
            final ClassPathResource classPathResource = new ClassPathResource("itDevices.json");
            fis = new BufferedInputStream(classPathResource.getInputStream());
            final byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            final String json = new String(buffer);
            return JSON.parseObject(json);
        } catch (final Exception e) {
            ItSynApiServiceImpl.log.error("", e);
        } finally {
            try {
                fis.close();
            } catch (final IOException e) {
            }
        }

        final String json =
                "{\"iTDevices\":[{\"id\":72198,\"dataCenterId\":758528777,\"dataCenterName\":\"中国移动（云南昆明）枢纽数据中心\",\"buildingName\":\"枢纽生产楼\",\"roomName\":\"五华区昆明枢纽楼三楼IDC机房\",\"roomId\":61605,\"rackName\":\"五华区昆明枢纽楼三楼IDC机房/SBJJ01-IDC-E13\",\"tenantId\":null,\"tenantName\":null,\"sellerName\":null,\"company\":null,\"tenantType\":null,\"indentId\":null,\"indentName\":null,\"submitDept\":null,\"name\":\"YNKM-PS-IDC01-WAF01-WAG5010\",\"coding\":\"YNKM-PS-IDC01-WAF01-WAG5010\",\"assetTag\":null,\"intId\":null,\"mountDate\":null,\"maintenanceDate\":null,\"networking\":false,\"monitoring\":false,\"netTier\":null,\"evaluation\":false,\"status\":\"在服\",\"contactNameNum\":null,\"spec\":{\"deviceCategory\":\"安全设备\",\"deviceType\":\"WAF\",\"producer\":\"启明星辰\",\"model\":\"WAG5010\",\"sn\":null,\"size\":{\"depth\":null,\"width\":null,\"height\":null},\"weight\":null,\"power\":{\"powerType\":null,\"voltage\":null,\"rated\":null,\"totalPowerRated\":null,\"totalActualPower\":null,\"actual\":null,\"powerConsumeType\":null,\"powerAccessMethod\":null,\"assetCode\":null},\"units\":2,\"slots\":null,\"spec\":null},\"rack\":{\"id\":61665,\"rackType\":\"自有业务\",\"name\":\"五华区昆明枢纽楼三楼IDC机房/SBJJ01-IDC-E13\",\"coding\":\"RACK-871-01-01-301-E13\",\"leaseStatus\":\"占用\",\"status\":\"在服\",\"spec\":\"五千瓦功率机柜\",\"roomName\":\"五华区昆明枢纽楼三楼IDC机房\",\"roomId\":61605,\"totalUnit\":42,\"testTotalUnit\":0,\"entire\":false,\"col\":5,\"colEn\":null,\"ordinal\":13,\"locationLabel\":null,\"plannedUse\":null,\"setupTime\":null,\"retireNetTime\":null,\"useCorp\":null,\"relatedSupplyCompany\":null,\"integrateAir\":null,\"powerSupplyType\":null,\"coldPartCode\":null,\"coldChildPartCode\":null,\"rackStatus\":null,\"shortName\":null,\"assetCoding\":null,\"occupy\":null,\"occupyUposNum\":null,\"idleUposNum\":null,\"size\":null,\"depth\":null,\"width\":null,\"height\":null,\"power\":{\"powerType\":\"AC\",\"voltage\":null,\"rated\":5000.0000,\"totalPowerRated\":null,\"totalActualPower\":null,\"actual\":null,\"powerConsumeType\":null,\"powerAccessMethod\":null,\"assetCode\":null},\"rated\":5000.0000,\"powerType\":\"AC\",\"powerConsumeType\":null,\"pdf\":\"RACK-871-01-01-301-E00\",\"ups\":\"Kin1 四楼电力机房2 4#UPS系统1#UPS输出柜 D10 K4 250A Kin2 四楼电力机房2 4#UPS系统2#UPS输出柜 D11 K4 250A\",\"intId\":null},\"startUnit\":18,\"endUnit\":19,\"mountOperatedTime\":null,\"portTotal\":null,\"idlePortTotal\":null,\"remark\":null,\"asset\":null,\"snmp\":{\"hostid\":null,\"proxyid\":null,\"templateid\":[],\"ip\":null,\"port\":161,\"ver\":\"V2C\",\"community\":null,\"internetIp\":null},\"ipAddresses\":null,\"outlets\":null,\"projectName\":null,\"businessOwner\":null,\"ipv4Manage\":null,\"ipv6Manage\":null,\"setupTime\":null,\"rackSurface\":null,\"lifecycleStatus\":null,\"businessDesc\":null,\"deviceCategory\":\"安全设备\",\"depth\":null,\"width\":null,\"height\":null,\"deviceType\":null,\"slots\":null,\"sn\":null,\"specJson\":null,\"units\":2,\"weight\":null,\"powerType\":null,\"rated\":null,\"voltage\":null,\"powerConsumeType\":null,\"powerAccessMethod\":null,\"propertyType\":null,\"direction\":null,\"powerConsume\":null,\"calorificValue\":null,\"serverRam\":null,\"cpu\":null,\"disk\":null,\"actual\":null,\"powerOnDto\":null,\"useRate\":null},{\"id\":72199,\"dataCenterId\":758528777,\"dataCenterName\":\"中国移动（云南昆明）枢纽数据中心\",\"buildingName\":\"枢纽生产楼\",\"roomName\":\"五华区昆明枢纽楼三楼IDC机房\",\"roomId\":61605,\"rackName\":\"五华区昆明枢纽楼三楼IDC机房/SBJJ01-IDC-Q10\",\"tenantId\":null,\"tenantName\":null,\"sellerName\":null,\"company\":null,\"tenantType\":null,\"indentId\":null,\"indentName\":null,\"submitDept\":null,\"name\":\"YNKM-PS-IDC01-WAF02-WAG5010\",\"coding\":\"YNKM-PS-IDC01-WAF02-WAG5010\",\"assetTag\":null,\"intId\":null,\"mountDate\":null,\"maintenanceDate\":null,\"networking\":false,\"monitoring\":false,\"netTier\":null,\"evaluation\":false,\"status\":\"在服\",\"contactNameNum\":null,\"spec\":{\"deviceCategory\":\"安全设备\",\"deviceType\":\"WAF\",\"producer\":\"启明星辰\",\"model\":\"WAG5010\",\"sn\":null,\"size\":{\"depth\":null,\"width\":null,\"height\":null},\"weight\":null,\"power\":{\"powerType\":null,\"voltage\":null,\"rated\":null,\"totalPowerRated\":null,\"totalActualPower\":null,\"actual\":null,\"powerConsumeType\":null,\"powerAccessMethod\":null,\"assetCode\":null},\"units\":2,\"slots\":null,\"spec\":null},\"rack\":{\"id\":61818,\"rackType\":\"自有业务\",\"name\":\"五华区昆明枢纽楼三楼IDC机房/SBJJ01-IDC-Q10\",\"coding\":\"RACK-871-01-01-301-Q10\",\"leaseStatus\":\"占用\",\"status\":\"在服\",\"spec\":\"五千瓦功率机柜\",\"roomName\":\"五华区昆明枢纽楼三楼IDC机房\",\"roomId\":61605,\"totalUnit\":42,\"testTotalUnit\":0,\"entire\":false,\"col\":17,\"colEn\":null,\"ordinal\":10,\"locationLabel\":null,\"plannedUse\":null,\"setupTime\":null,\"retireNetTime\":null,\"useCorp\":null,\"relatedSupplyCompany\":null,\"integrateAir\":null,\"powerSupplyType\":null,\"coldPartCode\":null,\"coldChildPartCode\":null,\"rackStatus\":null,\"shortName\":null,\"assetCoding\":null,\"occupy\":null,\"occupyUposNum\":null,\"idleUposNum\":null,\"size\":null,\"depth\":null,\"width\":null,\"height\":null,\"power\":{\"powerType\":\"AC\",\"voltage\":null,\"rated\":5000.0000,\"totalPowerRated\":null,\"totalActualPower\":null,\"actual\":null,\"powerConsumeType\":null,\"powerAccessMethod\":null,\"assetCode\":null},\"rated\":5000.0000,\"powerType\":\"AC\",\"powerConsumeType\":null,\"pdf\":\"RACK-871-01-01-301-Q00\",\"ups\":\"Kin1 四楼电力机房2 6#UPS系统1#UPS输出柜 H08 K1 250A Kin2 四楼电力机房2 6#UPS系统2#UPS输出柜 H09 K1 250A\",\"intId\":null},\"startUnit\":18,\"endUnit\":19,\"mountOperatedTime\":null,\"portTotal\":null,\"idlePortTotal\":null,\"remark\":null,\"asset\":null,\"snmp\":{\"hostid\":null,\"proxyid\":null,\"templateid\":[],\"ip\":null,\"port\":161,\"ver\":\"V2C\",\"community\":null,\"internetIp\":null},\"ipAddresses\":null,\"outlets\":null,\"projectName\":null,\"businessOwner\":null,\"ipv4Manage\":null,\"ipv6Manage\":null,\"setupTime\":null,\"rackSurface\":null,\"lifecycleStatus\":null,\"businessDesc\":null,\"deviceCategory\":\"安全设备\",\"depth\":null,\"width\":null,\"height\":null,\"deviceType\":null,\"slots\":null,\"sn\":null,\"specJson\":null,\"units\":2,\"weight\":null,\"powerType\":null,\"rated\":null,\"voltage\":null,\"powerConsumeType\":null,\"powerAccessMethod\":null,\"propertyType\":null,\"direction\":null,\"powerConsume\":null,\"calorificValue\":null,\"serverRam\":null,\"cpu\":null,\"disk\":null,\"actual\":null,\"powerOnDto\":null,\"useRate\":null},{\"id\":34643,\"dataCenterId\":758498710,\"dataCenterName\":\"中国移动（云南昆明）呈贡数据中心\",\"buildingName\":\"呈贡生产楼\",\"roomName\":\"呈贡县通信生产楼七楼数据机房1\",\"roomId\":110,\"rackName\":\"呈贡县通信生产楼七楼数据机房1/ZHJJ1-701-C15\",\"tenantId\":null,\"tenantName\":null,\"sellerName\":null,\"company\":null,\"tenantType\":null,\"indentId\":null,\"indentName\":null,\"submitDept\":null,\"name\":\"YNKM-PS-IDC03-NMASW03-701_C15\",\"coding\":\"YNKM-PS-IDC03-NMASW03-701_C15\",\"assetTag\":null,\"intId\":null,\"mountDate\":null,\"maintenanceDate\":null,\"networking\":true,\"monitoring\":false,\"netTier\":\"接入\",\"evaluation\":false,\"status\":\"在服\",\"contactNameNum\":null,\"spec\":{\"deviceCategory\":\"网络设备\",\"deviceType\":\"交换机\",\"producer\":\"迈普\",\"model\":\"S4220\",\"sn\":\"B387164481803987\",\"size\":{\"depth\":null,\"width\":null,\"height\":null},\"weight\":null,\"power\":{\"powerType\":\"AC\",\"voltage\":null,\"rated\":null,\"totalPowerRated\":null,\"totalActualPower\":null,\"actual\":null,\"powerConsumeType\":null,\"powerAccessMethod\":null,\"assetCode\":null},\"units\":1,\"slots\":null,\"spec\":null},\"rack\":{\"id\":553,\"rackType\":\"网络柜\",\"name\":\"呈贡县通信生产楼七楼数据机房1/ZHJJ1-701-C15\",\"coding\":\"RACK-871-03-01-701-C15\",\"leaseStatus\":\"占用\",\"status\":\"在服\",\"spec\":\"普通机柜\",\"roomName\":\"呈贡县通信生产楼七楼数据机房1\",\"roomId\":110,\"totalUnit\":48,\"testTotalUnit\":0,\"entire\":true,\"col\":3,\"colEn\":null,\"ordinal\":15,\"locationLabel\":null,\"plannedUse\":null,\"setupTime\":null,\"retireNetTime\":null,\"useCorp\":null,\"relatedSupplyCompany\":null,\"integrateAir\":null,\"powerSupplyType\":null,\"coldPartCode\":null,\"coldChildPartCode\":null,\"rackStatus\":null,\"shortName\":null,\"assetCoding\":null,\"occupy\":null,\"occupyUposNum\":null,\"idleUposNum\":null,\"size\":{\"depth\":600.0000,\"width\":1200.0000,\"height\":2200.0000},\"depth\":600.0000,\"width\":1200.0000,\"height\":2200.0000,\"power\":{\"powerType\":\"AC\",\"voltage\":null,\"rated\":4500.0000,\"totalPowerRated\":null,\"totalActualPower\":null,\"actual\":null,\"powerConsumeType\":null,\"powerAccessMethod\":null,\"assetCode\":null},\"rated\":4500.0000,\"powerType\":\"AC\",\"powerConsumeType\":null,\"pdf\":\"RACK-871-03-01-701-C00\",\"ups\":\"六楼下半区1#ups1#交流输出屏1QFn六楼下半区2#ups1#交流输出屏9QF\",\"intId\":null},\"startUnit\":7,\"endUnit\":7,\"mountOperatedTime\":null,\"portTotal\":null,\"idlePortTotal\":null,\"remark\":null,\"asset\":null,\"snmp\":{\"hostid\":null,\"proxyid\":null,\"templateid\":[],\"ip\":null,\"port\":161,\"ver\":\"V2C\",\"community\":null,\"internetIp\":null},\"ipAddresses\":null,\"outlets\":null,\"projectName\":\"IDC\",\"businessOwner\":null,\"ipv4Manage\":null,\"ipv6Manage\":null,\"setupTime\":null,\"rackSurface\":null,\"lifecycleStatus\":null,\"businessDesc\":null,\"deviceCategory\":\"网络设备\",\"depth\":null,\"width\":null,\"height\":null,\"deviceType\":null,\"slots\":null,\"sn\":\"B387164481803987\",\"specJson\":null,\"units\":1,\"weight\":null,\"powerType\":\"AC\",\"rated\":null,\"voltage\":null,\"powerConsumeType\":null,\"powerAccessMethod\":null,\"propertyType\":null,\"direction\":null,\"powerConsume\":null,\"calorificValue\":null,\"serverRam\":null,\"cpu\":null,\"disk\":null,\"actual\":null,\"powerOnDto\":null,\"useRate\":null}]}";
        return JSON.parseObject(json);
    }

    @Override
    public JSONObject getMockRackListData() {
        InputStream fis = null;
        try {
            final ClassPathResource classPathResource = new ClassPathResource("rackList.json");
            fis = new BufferedInputStream(classPathResource.getInputStream());
            final byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            final String json = new String(buffer);
            return JSON.parseObject(json);
        } catch (final Exception e) {
            ItSynApiServiceImpl.log.error("", e);
        } finally {
            try {
                fis.close();
            } catch (final IOException e) {
            }
        }
        final String json =
                "{\"rspCode\":\"0\",\"rspDesc\":\"成功\",\"rackList\":[{\"dataCenterCode\":\"中国移动（云南昆明）数据中心\",\"dataCenterName\":\"DC-871-04\",\"bulidingCode\":\"BD-871-04-B1\",\"buildingName\":\"B01生产楼\",\"roomCode\":\"RM-871-04-01-001\",\"roomName\":\"呈贡县中国移动（云南昆明）数据中心B01二楼201数据机房\",\"rackCode\":\"RACK-871-04-B1-201-A03\",\"rackName\":\"呈贡县中国移动（云南昆明）数据中心B01二楼201数据机房/IDC01-201-A03\",\"rackType\":\"政企业务\",\"leaseStatus\":\"空闲\",\"totalUnit\":49},{\"dataCenterCode\":\"中国移动（云南昆明）数据中心\",\"dataCenterName\":\"DC-871-04\",\"bulidingCode\":\"BD-871-04-B1\",\"buildingName\":\"B01生产楼\",\"roomCode\":\"RM-871-04-01-005\",\"roomName\":\"呈贡县中国移动（云南昆明）数据中心B01四楼401数据机房\",\"rackCode\":\"RACK-871-04-B1-401-I00\",\"rackName\":\"B01生产楼401-I00\",\"rackType\":\"政企业务\",\"leaseStatus\":\"空闲\",\"totalUnit\":49}]}";
        return JSON.parseObject(json);
    }

    @Override
    public JSONObject getItPortsData(final String deviceId) {
        final String url = this.getUrl("getItPortsData");
        final ParameterizedTypeReference<JSONObject> typeRef = new ParameterizedTypeReference<JSONObject>() {
        };
        final String param = "?deviceId=" + deviceId;
        final ResponseEntity<JSONObject> response =
                this.restTemplate.exchange(url + param, HttpMethod.GET, null, typeRef);
        if (null == response) {
            throw new UnitedException(url + "查询失败");
        }

        final JSONObject result = response.getBody();

        return result;
    }

    @Override
    public JSONObject getItPortFlowData(final String portTrafficId, final String startTime, final String endTime) {
        final String url = this.getUrl("getItPortFlowData");
        final ParameterizedTypeReference<JSONObject> typeRef = new ParameterizedTypeReference<JSONObject>() {
        };
        final String param = "?portTrafficId=" + portTrafficId + "&startTime=" + startTime + "&endTime=" + endTime;
        final ResponseEntity<JSONObject> response =
                this.restTemplate.exchange(url + param, HttpMethod.GET, null, typeRef);
        if (null == response) {
            throw new UnitedException(url + "查询失败");
        }
        final JSONObject result = response.getBody();

        return result;
    }

}
